package com.zenithmind.gateway.filter;

import com.zenithmind.gateway.auth.TokenExtractor;
import com.zenithmind.gateway.auth.UserInfoParser;
import com.zenithmind.gateway.auth.RequestHeaderSetter;
import com.zenithmind.gateway.security.SecurityPolicyHandler;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关统一认证过滤器
 * 整合多个认证相关过滤器的功能:
 * 1. 提取并解析JWT令牌
 * 2. 将用户信息转发给下游服务
 * 3. 为公开路径添加访客身份信息
 * 4. 添加网关验证标记
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GatewayAuthFilter implements GlobalFilter, Ordered {

    private final SecurityPolicyHandler securityPolicyHandler;
    private final TokenExtractor tokenExtractor;
    private final UserInfoParser userInfoParser;
    private final RequestHeaderSetter requestHeaderSetter;

    @Value("${zenithmind.gateway.auth.enabled:true}")
    private boolean authEnabled;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        String method = request.getMethod().name();

        log.debug("GatewayAuthFilter处理请求: {} {}", method, path);

        // 如果认证功能未启用，直接放行
        if (!authEnabled) {
            log.debug("认证功能未启用，直接放行请求: {}", path);
            return chain.filter(exchange);
        }

        ServerHttpRequest.Builder requestBuilder = request.mutate();

        // 1. 添加网关验证头，表示该请求来自网关
        requestHeaderSetter.setGatewayVerificationHeaders(requestBuilder);

        // 2. 检查是否是公开路径但需要添加访客身份
        boolean isPublicPathNeedingAuthRelay = isPublicPathNeedingAuthRelay(path);

        // 3. 获取token
        String token = tokenExtractor.extractToken(request);

        if (StringUtils.isBlank(token)) {
            // 如果没有token但是公开路径需要访客身份
            if (isPublicPathNeedingAuthRelay) {
                requestHeaderSetter.setGuestInfoHeaders(requestBuilder);
                log.debug("为公开路径{}添加模拟访客认证信息", path);
            }
        } else {
            // 如果有token，尝试解析
            try {
                UserInfoParser.UserInfo userInfo = userInfoParser.parseUserInfo(token);
                requestHeaderSetter.setUserInfoHeaders(requestBuilder, userInfo);
                log.debug("token解析成功，转发请求: {}, 用户ID: {}", path, userInfo.getUserId());
            } catch (Exception e) {
                // Token解析失败，记录日志但继续处理
                log.warn("Token解析失败，但仍放行请求: {}, 错误: {}", path, e.getMessage());
            }
        }

        // 使用修改后的请求继续处理链
        ServerHttpRequest modifiedRequest = requestBuilder.build();
        return chain.filter(exchange.mutate().request(modifiedRequest).build());
    }

    /**
     * 判断给定路径是否是需要中继认证信息的公开路径
     */
    private boolean isPublicPathNeedingAuthRelay(String path) {
        return path.contains("/api/zenithMind/course/") ||
               path.contains("/api/zenithMind/courses/") ||
               (path.startsWith("/api/zenithMind/") &&
                (path.contains("/public/") || path.contains("/statistics/")));
    }

    @Override
    public int getOrder() {
        return -100; // 高优先级，确保在其他过滤器之前执行
    }
} 